//Copyright 2012 Trevin Liberty
//GNU GPL v3
//Author: Trevin Liberty

#include "Barracks.h"

ALLEGRO_BITMAP** Barracks::images = NULL;

Barracks::Barracks(Map* map, Point<int> pos) : Doohickey(10000, map, Point<int>(288, 336)) {
	selected = false;

	this->pos = pos;
	unitBuildTimer = -1;

	loadImages();
}

void Barracks::loadImages() {
	if(images == NULL) {
		images = new ALLEGRO_BITMAP*[2];
		images[0] = al_load_bitmap("rsc/Objects/Barracks/BarracksC.tga");
		images[1] = al_load_bitmap("rsc/Objects/Barracks/BarracksO.tga");
	}
}

void Barracks::draw(Point<float> cameraPos) {
	if(selected) {
		al_draw_ellipse(pos.x - cameraPos.x + 125, pos.y - cameraPos.y + 225, 150, 150, al_map_rgb(50, 255, 50), 5);
		al_draw_bitmap(images[1], pos.x - cameraPos.x, pos.y - cameraPos.y, 0);
	}
	else
		al_draw_bitmap(images[0], pos.x - cameraPos.x, pos.y - cameraPos.y, 0);

	if(unitBuildTimer > 0) {
		float per = (al_get_time() - unitBuildTimer) / 2.5;
		float length = 256*per;
		al_draw_filled_rectangle(pos.x - cameraPos.x, pos.y - cameraPos.y + 350,
			pos.x - cameraPos.x + length, pos.y - cameraPos.y + 360, al_map_rgb(200, 200, 200));
	}
} 

bool Barracks::setEntityPos(Entity* e) {
	Point<int> p1;
	p1.x = pos.x/32.0 - 1;
	p1.y = pos.y/32.0 + 3;

	Point<int> p2;
	p2.x = p1.x + 10;
	p2.y = p1.y + 8;

	//left column of barracks
	for(int i = p1.y; i <= p2.y; i++) {
		if(i < 0 || i >= map->numTilesY)
			continue;
		if(map->mapArray[p1.x][i]->walkable &&
			map->mapArray[p1.x][i]->doohickey == NULL) {
				e->setXY(p1.x*32, i*32);
				return true;
		}
	}
	//bottom row of barracks
	for(int i = p1.x; i <= p2.x; i++) {
		if(i < 0 || i >= map->numTilesY)
			continue;
		if(map->mapArray[i][p2.y]->walkable &&
			map->mapArray[i][p2.y]->doohickey == NULL) {
				e->setXY(i*32, p2.y*32);
				return true;
		}
	}
	return false;
}

bool Barracks::update(Entity* e) {
	if(unitBuildTimer < 0)
		unitBuildTimer = al_get_time();
	else if(al_get_time() - unitBuildTimer > 2.5) {
		if(setEntityPos(e)) {
			unitBuildTimer = -1;
			return true;
		}
		return false;
	}
	return false;
}